package com.houxm.jbapu.pool;

import java.sql.SQLException;
import java.util.Hashtable;

import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;

public class ConnectionPoolFactory {
	
	static Hashtable<String, ConnectionPool> connectionPools = new Hashtable<String, ConnectionPool>(2, 0.75F);
	
	public static ConnectionPool lookup(ConnectionParam param) throws NameNotFoundException {
        return lookup(param.getName());
	}
	
	public static ConnectionPool lookup(String connectionPoolName) throws NameNotFoundException {
		ConnectionPool cp = connectionPools.get(connectionPoolName);
        if(cp == null || !(cp instanceof ConnectionPool))
            throw new NameNotFoundException(connectionPoolName);
        return cp;
	}
	
	public static ConnectionPool newInstance(ConnectionParam param)
	        throws NameAlreadyBoundException,ClassNotFoundException,
	                IllegalAccessException,InstantiationException,SQLException {
		ConnectionPool cp = null;
		try {
			lookup(param.getName());
		} catch (NameNotFoundException e) {
			cp = new ConnectionPool(param);
			connectionPools.put(param.getName(), cp);
		}
		return cp;
	}
	
	public static void free(String name) {
		ConnectionPool cp = null;
		try {
			cp = lookup(name);
			cp.close();
			connectionPools.remove(name);
			cp = null;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
}

